<template>
    <div>
        <div class="table-title">
            <h3>个人论文管理</h3>
        </div>
        <div class="user-show">
            <div class="user-table">
                <div class="user-table-utils">
                    <!-- <div>
                        <el-input placeholder="请输入查询内容" v-model="searchContent" class="input-with-select">
                            <el-select v-model="searchItem" slot="prepend" placeholder="请选择查询项">
                                <el-option v-for="item in searchItems" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                            <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
                        </el-input>
                    </div> -->
                    <div>
                        <el-button type="success" plain icon="el-icon-plus" @click="handleAdd">发布论文</el-button>
                    </div>
                </div>
                <el-table :data="tableData" border style="width: 100%" v-loading="tableLoading">
                    <el-table-column prop="thesisId" label="论文编号">
                    </el-table-column>
                    <el-table-column prop="name" label="论文课题">
                    </el-table-column>
                    <el-table-column prop="thesis" label="论文">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" :content="scope.row.filename" placement="top">
                                <el-button type="text" @click="downloadThesis(scope.row.filename)">{{ scope.row.thesis ?
                                    "下载论文" : "" }}</el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column prop="teacher" label="导师">
                    </el-table-column>
                    <el-table-column prop="press" label="出版社">
                    </el-table-column>
                    <el-table-column prop="time" label="发行时间">
                    </el-table-column>
                    <el-table-column prop="updateTime" label="更新时间">
                    </el-table-column>
                    <el-table-column prop="examed" label="审批状态">
                        <template slot-scope="scope">
                            <div slot="reference" class="name-wrapper">
                                <el-tag v-if="scope.row.examed === '已通过'" size="medium" type="success">{{ scope.row.examed
                                }}</el-tag>
                                <el-tag v-else-if="scope.row.examed === '未审批'" size="medium" type="warning">{{
                                    scope.row.examed }}</el-tag>
                                <el-tag v-else size="medium" type="danger">{{ scope.row.examed }}</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" style="margin-right: 10px;"
                                @click="handleEdit(scope.row)">修改</el-button>

                            <el-popconfirm title="确定删除吗？" @confirm="handleDel(scope.row)">
                                <el-button :loading="delLoading" slot="reference" type="text" size="small">删除</el-button>
                            </el-popconfirm>

                        </template>
                    </el-table-column>
                </el-table>
                <div class="user-pagination">
                    <el-pagination background small layout="prev, pager, next" :total="pagination.total"
                        :page-size="pagination.pageSize" :current-page="pagination.current"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                <el-form-item label="论文课题" prop="name">
                    <el-input type="text" v-model="ruleForm.name" autocomplete="off" clearable />
                </el-form-item>

                <el-form-item label="论文编号" prop="thesisId">
                    <el-input type="text" v-model="ruleForm.thesisId" autocomplete="off" clearable />
                </el-form-item>

                <el-form-item label="导师" prop="teacher">
                    <el-select v-model="ruleForm.teacher" filterable placeholder="请选择导师">
                        <el-option v-for="item in teacherList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="出版社" prop="press">
                    <el-select v-model="ruleForm.press" placeholder="请选择出版社">
                        <el-option v-for="item in pressList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="论文" prop="thesis">
                    <tapUpload acceptType="thesis" @change="handleChangeUpload($event)" />
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handleExit">取 消</el-button>
                <el-button type="success" plain @click="handleSubmit" :loading="editLoading">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import apis from '@/utils/api';
import request from '@/utils/requestMethod';
import './style.less';
import ifAdmin from '@/utils/judgeAdmin';
import { Message } from 'element-ui';
import tapUpload from '@/components/TapUpload/tapUpload.vue';
import axios from 'axios';

export default {
    name: 'personThesis',
    mounted() {
        this.getAuthorList();
        this.getPressList();
        this.getTeacherList();
        this.fetchThesis();
        this.userRole = ifAdmin();
    },
    components: {
        tapUpload
    },
    data() {

        /**
         *  对论文课题进行校验
         */
        const validateName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入论文课题'));
            } else {
                callback();
            }
        };

        /**
         *  对论文编号进行校验
         */
        const validateThesisId = (rule, value, callback) => {
            if (value === '' || value === undefined) {
                callback(new Error('请输入论文编号'));
            } else {
                callback();
            }
        };

        /**
         *  对著作人进行校验
         */
        const validateAuthor = (rule, value, callback) => {
            if (value === '' || value === undefined) {
                callback(new Error('请选择著作人'));
            } else {
                callback();
            }
        };

        /**
         *  对导师进行校验
         */
        const validateTeacher = (rule, value, callback) => {
            if (value === '' || value === undefined) {
                callback(new Error('请选择导师'));
            } else {
                callback();
            }
        };

        /**
         *  对学院进行校验
         */
        const validatePress = (rule, value, callback) => {
            if (value === '' || value === undefined) {
                callback(new Error('请选择出版社'));
            } else {
                callback()
            }
        };

        return {
            dialogVisible: false,
            tableLoading: false,
            delLoading: false,
            editLoading: false,
            tableData: [],
            userRole: false,
            searchItem: '',
            dialogTitle: '发布论文',
            searchItems: [
                {
                    label: '全部',
                    value: 'all'
                },
                {
                    label: '论文编号',
                    value: 'thesisId'
                },
                {
                    label: '论文课题',
                    value: 'name'
                },
                {
                    label: '出版社',
                    value: 'press'
                }
            ],
            searchContent: '',
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0
            },
            editRow: {},
            ifSave: true,
            ifSearch: false,
            authorList: [],
            pressList: [],
            teacherList: [],

            ruleForm: {
                name: '',
                thesisId: '',
                teacher: '',
                press: ''
            },
            rules: {
                name: [
                    { validator: validateName, trigger: 'blur' }
                ],
                thesisId: [
                    { validator: validateThesisId, trigger: 'blur' }
                ],
                author: [
                    { validator: validateAuthor, trigger: 'blur' }
                ],
                teacher: [
                    { validator: validateTeacher, trigger: 'blur' }
                ],
                press: [
                    { validator: validatePress, trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        /**
         * 获取著作人列表
         */
        getAuthorList() {
            request(apis.getUserList).then(res => {
                const {
                    objects
                } = res.data;
                objects.forEach(item => {
                    item.label = item.name;
                    item.value = item.name;
                });

                this.authorList = objects;
            });
        },

        /**
         *  获取出版社列表
         */
        getPressList() {
            request(apis.getPressList).then(res => {
                const {
                    objects
                } = res.data;
                objects.forEach(item => {
                    item.label = item.name;
                    item.value = item.name;
                })

                this.pressList = objects;
            })
        },

        /**
         *  获取导师列表
         */
        getTeacherList() {
            request(apis.fetchTeacherList).then(res => {
                const {
                    objects
                } = res.data;
                objects.forEach(item => {
                    item.label = item.name;
                    item.value = item.name;
                })

                this.teacherList = objects;
            })
        },

        /**
         *  获取所有个人论文信息
         */
        fetchThesis() {
            this.tableLoading = true;
            const {
                pagination: {
                    current,
                    pageSize
                }
            } = this;

            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            const { id } = userInfo;

            const body = {
                current,
                pageSize,
                id
            }

            request(apis.fetchPersonThesis, {
                method: 'POST',
                body
            }).then(res => {
                const {
                    objects,
                    total
                } = res.data;

                this.pagination.total = total;
                this.tableData = objects;
            }).finally(() => {
                this.tableLoading = false;
            }).catch(() => {
                this.tableLoading = false;
            })
        },

        /**
         *  点击新增按钮事件
         */
        handleAdd() {
            this.ifSave = true;
            this.dialogVisible = true;
            this.dialogTitle = '发布论文';
            this.ruleForm = {
                name: '',
                workId: '',
                username: '',
                college: '',
                post: ''
            };
        },

        /**
         * 点击编辑按钮事件
         */
        handleEdit(row) {
            this.ifSave = false;
            this.dialogVisible = true;
            this.editRow = row;
            this.ruleForm = row;
            this.dialogTitle = '修改论文'
        },

        /**
         * 点击取消按钮事件
         */
        handleExit() {
            this.dialogVisible = false;
            this.editLoading = false;
        },

        /**
         *  处理新增或编辑表单提交事件
         */
        handleSubmit() {
            this.$refs['ruleForm'].validate((valid) => {
                const {
                    ruleForm,
                    editRow,
                    ifSave
                } = this;

                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                const {
                    id,
                    name
                } = userInfo;

                ruleForm.author = name;
                ruleForm.authorId = id;
                editRow.authorId = id;

                if (valid) {
                    this.editLoading = true;
                    if (!ifSave) {
                        for (const item in ruleForm) {
                            editRow[item] = ruleForm[item];
                        }
                        if (editRow.examed === '已驳回') {
                            editRow.examed = '未审批';
                        }
                    }

                    request(apis.saveOrUpdateThesis, {
                        method: 'POST',
                        body: ifSave ? ruleForm : editRow
                    }).then(res => {
                        const {
                            objects,
                            message
                        } = res.data;
                        if (objects) {
                            Message.success(message);
                            this.dialogVisible = false;
                        } else {
                            const errMessage = ifSave ? '发布论文失败' : '修改论文信息失败';
                            Message.warning(errMessage);
                        }
                    }).finally(() => {
                        this.fetchThesis();
                        this.editLoading = false;
                    }).catch(() => {
                        this.editLoading = false;
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });


        },

        /**
         * 处理表格删除事件
         */
        handleDel(row) {
            this.delLoading = true;
            request(apis.delThesis, {
                method: 'POST',
                body: row
            }).then(res => {
                const {
                    objects,
                    message
                } = res.data;
                if (objects) {
                    Message.success(message);
                }
            }).finally(() => {
                this.delLoading = false;
                this.fetchThesis();
            }).catch(() => {
                Message.error("删除失败");
                this.delLoading = false;
            })
        },

        /**
         * 处理翻页事件
         */
        handleCurrentChange(value) {
            this.pagination.current = value;
            if (this.ifSearch) {
                this.handleSearch();
            } else {
                this.fetchThesis();
            }
        },
        handleClose(done) {
            done();
        },

        /**
         *  处理搜索事件
         */
        handleSearch() {
            this.ifSearch = true;
            const {
                searchItem,
                searchContent,
                pagination: {
                    current,
                    pageSize
                }
            } = this;

            if (searchItem === 'all') {
                this.fetchThesis();
                this.searchContent = '';
                this.searchItem = '';
                this.ifSearch = false;
            } else {
                if (searchItem === '') {
                    Message.warning('请输入搜索项');
                }
                if (searchContent === '') {
                    Message.warning('请输入搜索内容');
                }
            }

            if (searchContent !== '' && searchItem !== '' && searchItem !== 'all') {
                let content = searchContent;
                const body = {
                    searchItem,
                    content,
                    current,
                    pageSize
                }
                this.tableLoading = true;
                request(apis.searchThesis, {
                    method: 'POST',
                    body
                }).then(res => {
                    const {
                        objects,
                        message,
                        total
                    } = res.data;

                    this.pagination.total = total;
                    this.tableData = objects;
                    Message.success(message);

                }).finally(() => {
                    this.tableLoading = false;
                }).catch(() => {
                    this.tableLoading = false;
                    Message.error('搜索失败');
                })
            }
        },
        handleChangeUpload(value) {
            this.ruleForm.thesis = value.id;
            this.ruleForm.filename = value.filename;
        },
        downloadThesis(value) {
            console.log(value);
            axios({
                method: 'GET',
                url: '/api' + apis.downloadThesis,
                params: {filename: value},
                responseType: 'blob'
            }).then(response => {
                // 创建一个 blob 对象，并创建 URL 对象
                const blob = new Blob([response.data]);
                const url = window.URL.createObjectURL(blob);
                // 创建 a 标签并设置下载链接并模拟点击
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', value);
                document.body.appendChild(link);
                link.click();
                // 删除临时对象
                URL.revokeObjectURL(url);
                document.body.removeChild(link);
            }).catch(() => {
                this.$message.error('下载失败，请重试！')
            });
        }
    }
}
</script>